package io.renren.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author hewangtong
 *
 */
public class ReadExcel {

    enum CellValueType{
        STRING("STRING"),
        DATE("DATE"),
        NUMERIC("NUMERIC");
        CellValueType(String value){}
    }

    // 总行数
    private int totalRows = 0;
    // 总条数
    private int totalCells = 0;
    // 错误信息接收器
    private String errorMsg;

    // 构造方法
    public ReadExcel() {
    }

    // 获取总行数
    public int getTotalRows() {
        return totalRows;
    }

    // 获取总列数
    public int getTotalCells() {
        return totalCells;
    }

    // 获取错误信息
    public String getErrorInfo() {
        return errorMsg;
    }

    public String getCellValue(Cell cell,CellValueType type){
        String result = null;
        if(cell == null || type == null){
            return null;
        }
        switch (type){
            case STRING :
                try{result = String.valueOf(cell.getStringCellValue());break;}catch (Exception e){}
                try{result = String.valueOf(cell.getNumericCellValue());break;}catch (Exception e){}
            case DATE :
                Date d = cell.getDateCellValue();
                try{result = DateUtils.format(d,DateUtils.DATE_PATTERN);break;}catch (Exception e){}
                try{result = String.valueOf(cell.getStringCellValue());break;}catch (Exception e){}
            case  NUMERIC :
                try{result = String.valueOf(cell.getNumericCellValue());break;}catch (Exception e){}
                try{result = String.valueOf(cell.getStringCellValue());break;}catch (Exception e){}
            default:
                result =  String.valueOf(cell.getRichStringCellValue());
        }
        return result;
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述：是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // @描述：是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

}